package com.xlongwei.info;

import java.util.Map;

import com.networknt.utility.StringUtils;
import com.xlongwei.info.model.User;
import com.xlongwei.info.util.InfoConfig;
import com.xlongwei.info.util.Users;
import com.xlongwei.info.util.Utils;

import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TextHandler implements HttpHandler {

	public void handleRequest(HttpServerExchange exchange) throws Exception {
		Map<String, Object> map = Utils.getMap(exchange);
		String username = (String) map.get("username");
		String password = (String) map.get("password");
		String token = (String) map.get("token");
		if (StringUtils.isBlank(token)) {
			boolean ok = Users.login(username, password);
			log.info("login={}", ok);
			if (ok) {
				token = Utils.token(username);
				log.info("token={}", token);
				answerText(exchange, token);
				return;
			}
		} else if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
			User operator = Users.user(Utils.username(token)), user = Users.user(username);
			if (operator != null && user != null
					&& (operator.getUser().equals(user.getUser()) || InfoConfig.INSTANCE.isAdmin(operator.getUser()))) {
				if (user != null) {
					user.setPass(password);
					user.setBan(false);
					Users.login(username, password);
					token = Utils.token(username);
					answerText(exchange, token);
					return;
				}
			}
		}
		exchange.endExchange();
	}

	public static void answerText(HttpServerExchange exchange, String text) throws Exception {
		exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
		exchange.getResponseSender().send(text);
	}
}
